package redisdeploylogic

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"os/exec"
	"strings"
	"sync"
	"time"
	"yunzhan/common/models"
	utils "yunzhan/common/utils"
	"yunzhan/rpc-server/internal/svc"
	agent "yunzhan/rpc-server/pb"
)

type DeployRedisClusterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeployRedisClusterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeployRedisClusterLogic {
	return &DeployRedisClusterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// DeployRedisCluster 集群部署
func (l *DeployRedisClusterLogic) DeployRedisCluster(in *agent.DeployRedisRequest) (*agent.DeployResponse, error) {
	if in.NodeInfo == nil {
		return &agent.DeployResponse{
			Code:    500,
			Message: "未配置节点信息, 无法执行Redis集群部署",
		}, errors.New("未配置节点信息, 无法执行Redis集群部署")
	}

	resp := &agent.DeployResponse{
		Code:    200,
		Message: "请求已接收，正在部署Redis集群",
	}

	go l.startDeployment(in)

	return resp, nil
}

func (l *DeployRedisClusterLogic) startDeployment(in *agent.DeployRedisRequest) {

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		// 创建 LogManager 实例
		logManager := models.NewLogManager(100, fmt.Sprintf("http://%s:%d", l.svcCtx.Config.RestServices["apiServer"].RestConf.Host, l.svcCtx.Config.RestServices["apiServer"].RestConf.Port))
		defer logManager.Close()

		// 创建 ComponentInfoManager 实例
		flushInterval := 5 * time.Second // 刷新间隔
		maxBatchSize := 100              // 最大批量大小
		retryDelay := 2 * time.Second    // 重试延迟
		maxRetries := 3                  // 最大重试次数

		// 创建 ComponentInfoManager 实例
		componentInfoManager := models.NewComponentInfoManager(
			1000,
			fmt.Sprintf("http://%s:%d", l.svcCtx.Config.RestServices["apiServer"].RestConf.Host, l.svcCtx.Config.RestServices["apiServer"].RestConf.Port),
			flushInterval,
			maxBatchSize,
			retryDelay,
			maxRetries)
		defer componentInfoManager.Close()

		packageDirectory := in.ConfigInfo.PackagePath
		rtrimDir := utils.Rtrim(packageDirectory, "/")
		redisVersion := in.ConfigInfo.ComponentName
		installPath := utils.Rtrim(in.ConfigInfo.InstallPath, "/")
		baseInfo := fmt.Sprintf("安装包存放目录: %s, Redis version: %s, Redis 安装目录: %s", rtrimDir, redisVersion, installPath)
		step := 1
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", baseInfo, "Redis", "Server")

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "执行组件安装路径检查...", "Redis", "Server")
		checkPathCommand := fmt.Sprintf(`
if [ ! -d "%s" ]; then
   sudo mkdir -p "%s"
fi
`, installPath, installPath)
		output, err := utils.ExecCommand(checkPathCommand)
		if err != nil {
			message := fmt.Sprintf("检查组件安装路径异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "检查组件安装路径完成", "Redis", "Server")

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "解压安装包...", "Redis", "Server")
		tarCommand := fmt.Sprintf("sudo tar -xzf %s/%s -C %s", rtrimDir, redisVersion, installPath)
		output, err = utils.ExecCommand(tarCommand)
		if err != nil {
			message := fmt.Sprintf("解压安装包异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "解压安装包完成", "Redis", "Server")

		redisPackageName := utils.Rtrim(redisVersion, ".tar.gz")
		redisHome := fmt.Sprintf("%s/%s", installPath, redisPackageName)

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "执行数据存储目录检查...", "Redis", "Server")
		checkDataPathCommand := fmt.Sprintf(`
if [ ! -d "%s" ]; then
   sudo mkdir -p "%s"
fi
sudo chown -R %s:%s %s
`, in.RedisConfig.Dir, in.RedisConfig.Dir, in.NodeInfo.Username, in.NodeInfo.Username, in.RedisConfig.Dir)
		output, err = utils.ExecCommand(checkDataPathCommand)
		if err != nil {
			message := fmt.Sprintf("检查数据存储目录异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "检查数据存储目录完成", "Redis", "Server")

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "修改组件所属用户组...", "Redis", "Server")
		chownCommand := fmt.Sprintf("sudo chown -R %s:%s %s", in.NodeInfo.Username, in.NodeInfo.Username, redisHome)
		output, err = utils.ExecCommand(chownCommand)
		if err != nil {
			message := fmt.Sprintf("修改组件所属用户组异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "修改组件所属用户组完成", "Redis", "Server")

		step++
		currentIP, currentIPErr := utils.GetCurrentInternalIP()
		if err != nil {
			message := fmt.Sprintf("%s: 无法获取当前主机IP: %v", in.NodeInfo.Host, currentIPErr)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Server")
			return
		}
		currentHost, currentHostErr := utils.GetCurrentHostname()
		if err != nil {
			message := fmt.Sprintf("%s: 无法获取当前主机名: %v", in.NodeInfo.Host, currentHostErr)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Server")
			return
		}

		requirePass, errRole := utils.Encrypt([]byte("68656c6c6f2077dg"), in.RedisConfig.RequirePass)
		if errRole != nil {
			logx.Errorf("密码加密异常: %v", errRole)
		}

		if utils.Contains(in.RedisConfig.MasterNodes, currentHost) || utils.Contains(in.RedisConfig.MasterNodes, currentIP) {
			step++
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "构建Redis Master配置文件...", "Redis", "Master")
			masterConfig := generateRedisClusterConfig(in.RedisConfig, redisHome, currentIP, in.RedisConfig.MasterPort)

			configFilePath := fmt.Sprintf("%s/conf/redis_%s.conf", redisHome, in.RedisConfig.MasterPort)
			writeConfigFileCommand := fmt.Sprintf("echo '%s' | sudo tee %s", masterConfig, configFilePath)
			output, err = utils.ExecCommand(writeConfigFileCommand)
			if err != nil {
				message := fmt.Sprintf("构建Redis Master配置文件异常: %v, output: %s", err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Master")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "构建Redis Master配置文件完成", "Redis", "Master")

			masterServiceFile := fmt.Sprintf(`[Unit]
Description=Redis In-Memory Data Store
Documentation=https://redis.io/documentation
After=network.target

[Service]
Type=forking
User=%s
Group=%s
ExecStart=%s/bin/redis-server %s/conf/redis_%s.conf
ExecReload=%s/bin/redis-cli -p %s -a %s config rewrite
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=true
Restart=on-failure
LimitNOFILE=65536
LimitMEMLOCK=infinity

[Install]
WantedBy=multi-user.target`,
				in.NodeInfo.Username,
				in.NodeInfo.Username,
				redisHome, redisHome,
				in.RedisConfig.MasterPort,
				redisHome,
				in.RedisConfig.MasterPort,
				in.RedisConfig.MasterAuth)

			step++
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("创建 redis-%s.service 文件...", in.RedisConfig.MasterPort), "Redis", "Master")
			writeServiceFileCommand := fmt.Sprintf("echo '%s' | sudo tee /etc/systemd/system/redis-%s.service", masterServiceFile, in.RedisConfig.MasterPort)
			output, err = utils.ExecCommand(writeServiceFileCommand)
			if err != nil {
				message := fmt.Sprintf("创建 redis-%s.service 文件异常: %v, output: %s", in.RedisConfig.MasterPort, err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Master")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("创建 redis-%s.service 文件...", in.RedisConfig.MasterPort), "Redis", "Master")

			step++
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("Starting Redis Master on port %s...", in.RedisConfig.MasterPort), "Redis", "Master")
			reloadSystemdCommand := fmt.Sprintf("sudo systemctl daemon-reload && sudo systemctl enable redis-%s.service --now", in.RedisConfig.MasterPort)
			output, err = utils.ExecCommand(reloadSystemdCommand)
			if err != nil {
				message := fmt.Sprintf("启动Redis Master服务异常: %v, output: %s", err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Master")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("启动Redis Master服务完成"), "Redis", "Master")
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("等待Redis Master服务完全启动"), "Redis", "Master")
			time.Sleep(3 * time.Second)
			step++
			statusCommand := fmt.Sprintf("sudo systemctl is-active redis-%s.service", in.RedisConfig.MasterPort)
			output, err = utils.ExecCommand(statusCommand)
			if err != nil || strings.TrimSpace(output) != "active" {
				message := fmt.Sprintf("Redis Master服务启动后未正常运行: %v, output: %s", err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Master")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("Redis Master服务部署成功"), "Redis", "Master")

			redisRole, errRole := utils.GetRedisRole(currentIP+":"+in.RedisConfig.MasterPort, in.RedisConfig.MasterAuth)
			if errRole != nil {
				logx.Errorf("查询Redis %s进程角色异常: %v", in.RedisConfig.MasterPort, errRole)
			}

			redisInfo := &models.ComponentInfo{
				ClusterID:      in.ClusterID,
				ComponentName:  "Redis",
				Version:        in.Version,
				NodeHost:       currentHost,
				NodeIP:         currentIP,
				ComponentRole:  redisRole,
				HomePath:       redisHome,
				Port:           in.RedisConfig.MasterPort,
				DataStorageDir: in.RedisConfig.Dir,
				Status:         true,
				AdditionalInfo: fmt.Sprintf("config_file=%s,require_pass=%s", configFilePath, requirePass),
			}

			componentInfoManager.SendComponentInfo(redisInfo)

		}

		if utils.Contains(in.RedisConfig.SlaveNodes, currentHost) || utils.Contains(in.RedisConfig.SlaveNodes, currentIP) {
			step++
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "构建Redis Slave配置文件...", "Redis", "Slave")
			slaveConfig := generateRedisClusterConfig(in.RedisConfig, redisHome, currentIP, in.RedisConfig.SlavePort)
			configFilePath := fmt.Sprintf("%s/conf/redis_%s.conf", redisHome, in.RedisConfig.SlavePort)
			writeConfigFileCommand := fmt.Sprintf("echo '%s' | sudo tee %s", slaveConfig, configFilePath)
			output, err = utils.ExecCommand(writeConfigFileCommand)
			if err != nil {
				message := fmt.Sprintf("构建Redis Slave配置文件异常: %v, output: %s", err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Slave")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "构建Redis Slave配置文件完成", "Redis", "Slave")

			slaveServiceFile := fmt.Sprintf(`[Unit]
Description=Redis In-Memory Data Store
Documentation=https://redis.io/documentation
After=network.target

[Service]
Type=forking
User=%s
Group=%s
ExecStart=%s/bin/redis-server %s/conf/redis_%s.conf
ExecReload=%s/bin/redis-cli -p %s -a %s config rewrite
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=true
Restart=on-failure
LimitNOFILE=65536
LimitMEMLOCK=infinity

[Install]
WantedBy=multi-user.target`,
				in.NodeInfo.Username,
				in.NodeInfo.Username,
				redisHome,
				redisHome,
				in.RedisConfig.SlavePort,
				redisHome,
				in.RedisConfig.SlavePort,
				in.RedisConfig.MasterAuth)

			step++
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("创建 redis-%s.service 文件...", in.RedisConfig.SlavePort), "Redis", "Slave")
			writeServiceFileCommand := fmt.Sprintf("echo '%s' | sudo tee /etc/systemd/system/redis-%s.service", slaveServiceFile, in.RedisConfig.SlavePort)
			output, err = utils.ExecCommand(writeServiceFileCommand)
			if err != nil {
				message := fmt.Sprintf("创建 redis-%s.service 文件异常: %v, output: %s", in.RedisConfig.SlavePort, err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Slave")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("创建 redis-%s.service 文件...", in.RedisConfig.SlavePort), "Redis", "Slave")

			step++
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("Starting Redis Slave on port %s...", in.RedisConfig.SlavePort), "Redis", "Slave")
			reloadSystemdCommand := fmt.Sprintf("sudo systemctl daemon-reload && sudo systemctl enable redis-%s.service --now", in.RedisConfig.SlavePort)
			output, err = utils.ExecCommand(reloadSystemdCommand)
			if err != nil {
				message := fmt.Sprintf("启动Redis Slave服务异常: %v, output: %s", err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Server")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("启动Redis Slave服务完成"), "Redis", "Slave")
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("等待Redis Slave服务完全启动"), "Redis", "Slave")
			time.Sleep(3 * time.Second)
			step++
			statusCommand := fmt.Sprintf("sudo systemctl is-active redis-%s.service", in.RedisConfig.SlavePort)
			output, err = utils.ExecCommand(statusCommand)
			if err != nil || strings.TrimSpace(output) != "active" {
				message := fmt.Sprintf("Redis Slave服务启动后未正常运行: %v, output: %s", err, output)
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Slave")
				return
			}
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", fmt.Sprintf("Redis Slave服务部署成功"), "Redis", "Slave")

			redisRole, errRole := utils.GetRedisRole(currentIP+":"+in.RedisConfig.SlavePort, in.RedisConfig.MasterAuth)
			if errRole != nil {
				logx.Errorf("查询Redis %s进程角色异常: %v", in.RedisConfig.SlavePort, errRole)
			}

			redisInfo := &models.ComponentInfo{
				ClusterID:      in.ClusterID,
				ComponentName:  "Redis",
				Version:        in.Version,
				NodeHost:       currentHost,
				NodeIP:         currentIP,
				ComponentRole:  redisRole,
				HomePath:       redisHome,
				Port:           in.RedisConfig.SlavePort,
				DataStorageDir: in.RedisConfig.Dir,
				Status:         true,
				AdditionalInfo: fmt.Sprintf("config_file=%s,require_pass=%s", configFilePath, requirePass),
			}

			componentInfoManager.SendComponentInfo(redisInfo)

		}

		if in.RedisConfig.MasterNodes[0] == currentIP || in.RedisConfig.MasterNodes[0] == currentHost {
			createCluster := func() {
				step++
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "创建Redis集群...", "Redis", "Master")

				time.Sleep(5 * time.Second)
				var allNodes []string
				for _, node := range in.RedisConfig.MasterNodes {
					allNodes = append(allNodes, fmt.Sprintf("%s:%s", node, in.RedisConfig.MasterPort))
				}
				for _, node := range in.RedisConfig.SlaveNodes {
					allNodes = append(allNodes, fmt.Sprintf("%s:%s", node, in.RedisConfig.SlavePort))
				}
				nodesStr := strings.Join(allNodes, " ")

				command := fmt.Sprintf("%s/bin/redis-cli -a %s --cluster create %s --cluster-replicas %s", redisHome, in.RedisConfig.MasterAuth, nodesStr, in.RedisConfig.ClusterReplicas)

				logx.Infof("创建集群: %s", command)

				cmd := exec.Command("sh", "-c", command)
				stdin, err := cmd.StdinPipe()
				if err != nil {
					message := fmt.Sprintf("创建Redis集群异常: %v, output: %v", err, stdin)
					logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Master")
					return
				}
				defer stdin.Close()

				var out bytes.Buffer
				cmd.Stdout = &out
				cmd.Stderr = &out

				err = cmd.Start()
				if err != nil {
					message := fmt.Sprintf("创建Redis集群异常: %v", err)
					logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Master")
					return
				}

				go func() {
					time.Sleep(2 * time.Second)
					stdin.Write([]byte("yes\n"))
				}()

				err = cmd.Wait()
				if err != nil {
					message := fmt.Sprintf("创建Redis集群异常: %v", err)
					logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Redis", "Master")
					return
				}
				logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "Redis集群创建完成", "Redis", "Master")
			}
			createCluster()
		}
	}()
	wg.Wait()

}

func generateRedisClusterConfig(config *agent.RedisConfig, redisHome, host, port string) string {
	var configBuilder strings.Builder
	configBuilder.WriteString(fmt.Sprintf("bind %s\n", host))

	configBuilder.WriteString(fmt.Sprintf("port %s\n", port))

	if config.Daemonize != "" {
		configBuilder.WriteString(fmt.Sprintf("daemonize %s\n", config.Daemonize))
	}

	configBuilder.WriteString(fmt.Sprintf("pidfile %s/redis_%s.pid\n", redisHome, port))

	if config.ProtectedMode != "" {
		configBuilder.WriteString(fmt.Sprintf("protected-mode %s\n", config.ProtectedMode))
	}

	if config.Loglevel != "" {
		configBuilder.WriteString(fmt.Sprintf("loglevel %s\n", config.Loglevel))
	}

	configBuilder.WriteString(fmt.Sprintf("logfile %s/logs/redis_%s.log\n", redisHome, port))

	if config.Databases != 0 {
		configBuilder.WriteString(fmt.Sprintf("databases %d\n", config.Databases))
	}

	if config.Save != nil && len(config.Save) > 0 {
		for key, value := range config.Save {
			configBuilder.WriteString(fmt.Sprintf("save %s %d\n", key, value))
		}
	}

	if config.StopWritesOnBgSaveError != "" {
		configBuilder.WriteString(fmt.Sprintf("stop-writes-on-bgsave-error %s\n", config.StopWritesOnBgSaveError))
	}

	if config.RdbCompression != "" {
		configBuilder.WriteString(fmt.Sprintf("rdbcompression %s\n", config.RdbCompression))
	}

	if config.RdbChecksum != "" {
		configBuilder.WriteString(fmt.Sprintf("rdbchecksum %s\n", config.RdbChecksum))
	}

	if config.DbFilename != "" {
		configBuilder.WriteString(fmt.Sprintf("dbfilename %s_%s\n", port, config.DbFilename))
	} else {
		configBuilder.WriteString(fmt.Sprintf("dbfilename dump.rdb\n"))
	}

	if config.Dir != "" {
		configBuilder.WriteString(fmt.Sprintf("dir %s\n", config.Dir))
	}

	if config.SlaveServeStaleData != "" {
		configBuilder.WriteString(fmt.Sprintf("slave-serve-stale-data %s\n", config.SlaveServeStaleData))
	}

	if config.SlaveReadOnly != "" {
		configBuilder.WriteString(fmt.Sprintf("slave-read-only %s\n", config.SlaveReadOnly))
	}

	if config.ReplDiskLessSync != "" {
		configBuilder.WriteString(fmt.Sprintf("repl-diskless-sync %s\n", config.ReplDiskLessSync))
	}

	if config.ReplDiskLessSyncDelay != "" {
		configBuilder.WriteString(fmt.Sprintf("repl-diskless-sync-delay %s\n", config.ReplDiskLessSyncDelay))
	}

	if config.SlavePriority != "" {
		configBuilder.WriteString(fmt.Sprintf("slave-priority %s\n", config.SlavePriority))
	}

	if strings.ToLower(config.AppendOnly) == "yes" {
		configBuilder.WriteString(fmt.Sprintf("appendonly %s\n", config.AppendOnly))
		configBuilder.WriteString(fmt.Sprintf("appendfilename %s_appendonly.aof\n", port))
		if config.Appendfsync != "" {
			configBuilder.WriteString(fmt.Sprintf("appendfsync %s\n", config.Appendfsync))
		}
	}

	if config.Timeout != "" {
		configBuilder.WriteString(fmt.Sprintf("timeout %s\n", config.Timeout))
	}

	if config.MaxMemory != "" {
		configBuilder.WriteString(fmt.Sprintf("maxmemory %s\n", config.MaxMemory))
	}
	if config.RequirePass != "" {
		configBuilder.WriteString(fmt.Sprintf("requirepass %s\n", config.RequirePass))
	}
	if config.MasterAuth != "" {
		configBuilder.WriteString(fmt.Sprintf("masterauth %s\n", config.MasterAuth))
	}

	configBuilder.WriteString(fmt.Sprintf("cluster-enabled yes\n"))

	if config.ClusterNodeTimeout != "" {
		configBuilder.WriteString(fmt.Sprintf("cluster-node-timeout %s\n", config.ClusterNodeTimeout))
	}

	configBuilder.WriteString(fmt.Sprintf("cluster-config-file nodes_%s.conf\n", port))

	return configBuilder.String()
}
